"""
InCloud 专业术语映射和处理模块
"""

import re
import yaml
import os
from typing import Dict, List, Tuple, Optional
import logging

logger = logging.getLogger(__name__)

def load_terminology_config() -> Dict:
    """加载术语配置文件"""
    try:
        # 获取配置文件路径
        current_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
        config_path = os.path.join(current_dir, 'terminology.yaml')

        if not os.path.exists(config_path):
            logger.warning(f"Terminology config file not found: {config_path}")
            return {}

        with open(config_path, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)

        logger.info(f"Loaded terminology config from {config_path}")
        return config

    except Exception as e:
        logger.error(f"Failed to load terminology config: {e}")
        return {}

# 加载术语配置
_terminology_config = load_terminology_config()

# 从配置中提取映射表（保持向后兼容）
TERMINOLOGY_MAPPING = {}
SERVICE_MAPPING = _terminology_config.get('service_mapping', {})

# 构建术语映射表
terminology_mapping = _terminology_config.get('terminology_mapping', {})
for term, config in terminology_mapping.items():
    aliases = config.get('aliases', [])
    TERMINOLOGY_MAPPING[term] = aliases

    # 为每个别名也创建映射
    for alias in aliases:
        if alias not in TERMINOLOGY_MAPPING:
            TERMINOLOGY_MAPPING[alias] = [term] + [a for a in aliases if a != alias]

class TerminologyProcessor:
    """术语处理器"""
    
    def __init__(self):
        self.mapping = TERMINOLOGY_MAPPING
        self.service_mapping = SERVICE_MAPPING
    
    def normalize_query(self, query: str) -> str:
        """
        标准化用户查询，将常见术语转换为标准形式

        Args:
            query: 用户输入的查询

        Returns:
            标准化后的查询
        """
        normalized = query

        # 从配置文件获取标准化规则
        normalization_rules = _terminology_config.get('normalization_rules', [])

        for rule in normalization_rules:
            pattern = rule.get('pattern', '')
            replacement = rule.get('replacement', '')
            if pattern and replacement:
                normalized = re.sub(pattern, replacement, normalized)

        logger.debug(f"Query normalized: '{query}' -> '{normalized}'")
        return normalized
    
    def get_related_terms(self, term: str) -> List[str]:
        """
        获取相关术语
        
        Args:
            term: 输入术语
            
        Returns:
            相关术语列表
        """
        term_lower = term.lower()
        for key, related in self.mapping.items():
            if key.lower() == term_lower:
                return related
        return []
    
    def explain_terminology(self, term: str) -> Optional[str]:
        """
        解释术语含义

        Args:
            term: 要解释的术语

        Returns:
            术语解释
        """
        # 从配置文件获取术语解释
        terminology_mapping = _terminology_config.get('terminology_mapping', {})

        # 直接查找
        if term in terminology_mapping:
            return terminology_mapping[term].get('description', '')

        # 查找别名
        for _, config in terminology_mapping.items():
            aliases = config.get('aliases', [])
            if term.lower() in [alias.lower() for alias in aliases]:
                return config.get('description', '')

        return None
    
    def suggest_correct_service(self, query: str) -> List[Tuple[str, str]]:
        """
        根据查询建议正确的服务
        
        Args:
            query: 用户查询
            
        Returns:
            (服务名, 建议原因) 的列表
        """
        suggestions = []
        query_lower = query.lower()
        
        # 检查查询中的关键词
        if any(term in query_lower for term in ['主机', '云主机', '虚拟主机', 'vhost', 'host']):
            suggestions.append(('icompute', '查询涉及虚拟主机(vhosts/云主机)，建议使用 icompute 服务'))
        
        if any(term in query_lower for term in ['虚拟机', 'vm', 'virtual machine']):
            suggestions.append(('icompute', '查询涉及虚拟机(vm)，建议使用 icompute 服务'))
        
        if any(term in query_lower for term in ['存储', '存储卷', '虚拟存储卷', 'volume', 'storage']):
            suggestions.append(('istorage', '查询涉及存储资源，建议使用 istorage 服务'))
        
        if any(term in query_lower for term in ['网络', '子网', 'network', 'subnet']):
            suggestions.append(('inetwork', '查询涉及网络资源，建议使用 inetwork 服务'))
        
        return suggestions

# 全局术语处理器实例
terminology_processor = TerminologyProcessor()

def get_terminology_reminder(language: str = 'cn') -> str:
    """
    获取术语提醒文本

    Args:
        language: 语言代码 ('cn' 或 'en')

    Returns:
        术语提醒文本
    """
    prompt_templates = _terminology_config.get('prompt_templates', {})
    terminology_reminder = prompt_templates.get('terminology_reminder', {})

    return terminology_reminder.get(language, terminology_reminder.get('cn', ''))

def get_concept_distinctions() -> Dict:
    """获取概念区别说明"""
    return _terminology_config.get('concept_distinctions', {})

def enhance_tool_description(original_description: str, service_name: str, path: str) -> str:
    """
    增强工具描述，添加术语说明

    Args:
        original_description: 原始描述
        service_name: 服务名称
        path: API 路径

    Returns:
        增强后的描述
    """
    enhanced = original_description

    # 从配置获取术语映射
    terminology_mapping = _terminology_config.get('terminology_mapping', {})

    # 根据路径添加术语说明
    path_lower = path.lower()

    # 检查路径中的关键词并添加相应说明
    for term, config in terminology_mapping.items():
        api_term = config.get('api_term', '')
        if api_term and api_term.lower() in path_lower:
            aliases = config.get('aliases', [])
            if aliases:
                alias_text = ' = '.join([term] + aliases[:3])  # 限制显示数量
                enhanced += f"\n\n📝 术语说明：{alias_text}"
            break

    # 添加服务说明
    if service_name in SERVICE_MAPPING:
        service_info = SERVICE_MAPPING[service_name]
        enhanced += f"\n\n🏷️ 服务：{service_info['name']} - {service_info['description']}"

    return enhanced

def reload_terminology_config():
    """重新加载术语配置"""
    global _terminology_config, TERMINOLOGY_MAPPING, SERVICE_MAPPING

    _terminology_config = load_terminology_config()
    SERVICE_MAPPING = _terminology_config.get('service_mapping', {})

    # 重新构建术语映射表
    TERMINOLOGY_MAPPING = {}
    terminology_mapping = _terminology_config.get('terminology_mapping', {})
    for term, config in terminology_mapping.items():
        aliases = config.get('aliases', [])
        TERMINOLOGY_MAPPING[term] = aliases

        # 为每个别名也创建映射
        for alias in aliases:
            if alias not in TERMINOLOGY_MAPPING:
                TERMINOLOGY_MAPPING[alias] = [term] + [a for a in aliases if a != alias]

    logger.info("Terminology configuration reloaded")
